require(['../../common'], function() {
  require(['cate.sitelist'])
})

define('cate.sitelist', [
  'jquery',
  'page/grid'
], function($, Grid) {
  'use strict';

  var $table = $('.table')
  var mygrid = new Grid($table)
  mygrid.init();

  function del(selected) {
		  //执行删除语句
		  var sid = $('#J_hideSid').val()
		    $.post(APP + '?app=cms&m=Cate&a=delCate', {
		      ids: selected.id.join(),
		      sid: sid
		    })
		      .done(function(data) {
		        if (data == '1') {
		          mygrid.del(selected.index)
		        } else {
		          alert('删除失败')
		        }
		      })
  }

  function move(id, el, index, nextIndex, direction) {
    var baseid = direction == 'up' ? $(el).closest('tr').prev().data('id') : $(el).closest('tr').next().data('id');
    if (baseid) {
      $.post(APP + '?app=cms&m=Cate&a=display_order', {
        id: id,
        baseid: baseid
      }).done(function(res) {
        if (res === '1') {
          mygrid.swap(index, nextIndex)
        }
      })
    }
  }

  $table

  // 删除当前行
  .on('click', '.A_del', function(e) {
    e.preventDefault()
    if(confirm("确认删除？")){
        var current = mygrid.getCurrent(this)
        var selected = {
          id: [current.id],
          index: [current.index]
        }
        del(selected)
    }
    
  })

  // 排序
  .on('click', '.moveup', function(e) {
    if ($(this).hasClass('disabled')) {
      return false
    }
    move($(this).closest('tr').data('id'), this, mygrid.getIndex(this), Number(mygrid.getIndex(this) - 1), 'up')
  })

  // 排序
  .on('click', '.movedown', function(e) {
    if ($(this).hasClass('disabled')) {
      return false
    }
    move($(this).closest('tr').data('id'), this, mygrid.getIndex(this), Number(mygrid.getIndex(this) + 1), 'down')
  })

  // 删除选中行
  $('#J_del').click(function(e) {
    e.preventDefault();
    if(confirm("确定删除？")){
        var selected = mygrid.getSelected()
        if (!selected.count) {
          alert(lang.pleaseSelectAData)
          return
        }
        del(selected)
    }

  });

  $(document)
    .on('change', '#J_sitelists', function() {
      var site_id = $(this).val()
      if (site_id > 0) {
        location.href = APP + '?app=cms&m=Cate&a=catelist&sid=' + site_id
      }else{
    	location.href = APP + '?app=cms&m=Cate&a=catelist'
      }
    })
    .ready(function() {
      if ($('#J_sitelists').val() > 0) {
        $('.datas-ft').show()
      }
    })
})
